[Coding001] LeetCode 1

Two Sum

Ben 2023/07/19

More coding records

Get the knowledge flowing and circulating! :)

目录

1. Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Example 2:

Example 3:

Constraints:

Follow-up: Can you come up with an algorithm that is less than O(n2)time complexity?

解题

解法1

解法1的时间复杂度分析

外层循环 0~n-1

内层循环最坏的情况下n-1次

所以时间复杂度是O(n2)

 


 

解法2

 

解法2的时间复杂度分析

全程一个for循环,能查到,就结束;查不到,就进行线性操作。

时间复杂度:O(n)

 

解题过程分析

设想target是目标,target由数组中的两个数相加得到。 数1数2 暂且称为互补的数。 答案要的是这两个数的索引值(即数组中的下标)。

  • 【情况1】使用HashMap,键存放数1,值存放数2的索引。遍历到数1的时候,由i标识,此时返回i数2的索引(键为数1时对应的)即构成答案。

  • 【情况2】HashMap如果找到的键对应的值为null,说明两种可能:①这个值没有互补的数,②这个值的互补数还没加入HashMap. 这两种情况可以统一处理。即,将该值的互补数计算出来,然后按照【情况1】进行操作。

 

知识点积累 (Java)

  1. 一维数组的初始化

  2. 直接返回一个数组的方法

  3. map的用法

    为什么要用HashMap?

    HashMap:基于哈希表的 Map 接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。(除了非同步和允许使用 null 之外,HashMap 类与 Hashtable 大致相同。)此类不保证映射的顺序,特别是它不保证该顺序恒久不变。 此实现假定哈希函数将元素适当地分布在各桶之间,可为基本操作(get 和 put)提供稳定的性能。迭代 collection 视图所需的时间与 HashMap 实例的“容量”(桶的数量)及其大小(键-值映射关系数)成比例。所以,如果迭代性能很重要,则不要将初始容量设置得太高(或将加载因子设置得太低)。

 

附(完整程序)